using UnityEngine;
using UnityEditor;

namespace LCH
{
    /// <summary>
    /// 网格绘制器 - UI绘制功能模块
    /// </summary>
    public partial class LchMeshPainter
    {
        /// <summary>
        /// 绘制主面板，包含工具栏和各个子面板
        /// </summary>
        void OnDrawMainPanel()
        {
            panelType = GUILayout.Toolbar(panelType, new string[] { Languages.GetValue(0,"Mesh Painter"), Languages.GetValue(1, "Terrain Tool"), Languages.GetValue(2, "Build tree tools"), Languages.GetValue(3, "Setting"), Languages.GetValue(4, "Help") });
            switch (panelType)
            {
                case 0:
                    {
                        OnDrawPainterPanel();
                    }
                    break;
                case 1:
                    {
                        OnDrawMeshPanel();
                    }
                    break;
                case 2:
                    {
                        OnDrawTreePainter();
                        
                    }
                    break;
                case 3:
                    {
                        OnDrawSetting();
                    }
                    break;
                case 4:
                    {
                        OnDrawHelp();
                    }
                    break;
            }
        }

        /// <summary>
        /// 绘制网格工具面板
        /// </summary>
        void OnDrawMeshPanel()
        {
            meshPanelType = 0;
            TerrainToMesh(); 
            
        }

        /// <summary>
        /// 绘制设置面板
        /// </summary>
        void OnDrawSetting()
        {
            EditorGUI.BeginChangeCheck();
            setting.ctrlTexturePrefix = EditorGUILayout.TextField(Languages.GetValue(13, "Control Texture Prefix"), setting.ctrlTexturePrefix);
            setting.flowMapTextureName = EditorGUILayout.TextField(Languages.GetValue(62, "FlowMap Texture"), setting.flowMapTextureName);
            
            setting.mainTexArray = EditorGUILayout.TextField(Languages.GetValue(59, "Texture2dArray "), setting.mainTexArray);
            setting.mainTexArrayIndex = EditorGUILayout.TextField(Languages.GetValue(65, "Texture2dArray Index"), setting.mainTexArrayIndex);

            setting.defaultTerrainShaderName = EditorGUILayout.TextField(Languages.GetValue(56, "Terrain default Shader name"), setting.defaultTerrainShaderName);
            setting.prefix = EditorGUILayout.TextField(Languages.GetValue(66, "Layer Texture  prefix"), setting.prefix);
            setting.norPrefix = EditorGUILayout.TextField(Languages.GetValue(67, "Normal Texture Prefix"), setting.norPrefix);

            GUILayout.Label(Languages.GetValue(52, "Export the terrain layers texture to  property of the material at ") + setting.prefix + "0," + setting.prefix + "1, " + setting.prefix + "2... ");
            GUILayout.Label(Languages.GetValue(53, "Export the terrain normals texture to  property of the material at ") + setting.norPrefix + "0," + setting.norPrefix + "1, " + setting.norPrefix + "2... ");

            setting.brushColor = EditorGUILayout.ColorField(Languages.GetValue(60,"Brush Color"), setting.brushColor);
            setting.drawingColor = EditorGUILayout.ColorField(Languages.GetValue(61, "Drawing Brush Color"),setting.drawingColor);
            
            //public Color drawingColor = new Color(0f, 0f, 0.5f, 0f);
            //public Color brushColor = new Color(0.5f, 0.5f, 0.5f, 0f);

            editorLayer = EditorGUILayout.IntSlider(Languages.GetValue(24, "Editor used Layer:"), editorLayer, 0, 30);
            if (Languages.languageNames.Length>0)
                Languages.curLanguage = EditorGUILayout.Popup(Languages.GetValue(25, "Language:"),Languages.curLanguage, Languages.languageNames);

            if (EditorGUI.EndChangeCheck())
            {
                SaveSetting();
            }
        }
        
        /// <summary>
        /// 绘制顶点颜色绘制面板
        /// </summary>
        void OnDrawVertexPainter()
        {
            EditorGUI.BeginChangeCheck();
            
            vertexBrushType = EditorGUILayout.Popup(Languages.GetValue(17, "Brush type:"),vertexBrushType, new string[] { Languages.GetValue(18, "Channels brush"), Languages.GetValue(19, "Custom Color")  });
            bool b = EditorGUI.EndChangeCheck();

            switch (vertexBrushType)
            {
                case 0:
                    {
                        GUILayout.Label(Languages.GetValue(15,"Channels:"));
                        EditorGUILayout.BeginHorizontal();
                        EditorGUILayout.Space(30, false);
                        string[] fourChanges = new string[4] {Languages.GetValue(100, "Channel 1"), Languages.GetValue(101, "Channel 2"), Languages.GetValue(102, "Channel 3"), Languages.GetValue(103, "Channel 4") };
                        editingChannel = GUILayout.SelectionGrid(editingChannel, fourChanges, 1);
                        EditorGUILayout.EndHorizontal();
                    }
                    break;
                case 1:
                    {
                        vertexBrushColor = EditorGUILayout.ColorField(Languages.GetValue(20,"Brush Color:"), vertexBrushColor);
                    }
                    break;
            }

            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button(Languages.GetValue(16, "Save")))
            {
                string path = AssetDatabase.GetAssetPath(selectObjectMesh);
                if (path.EndsWith(".mesh"))
                {
                    selectObjectMesh.colors = baseColors;
                    EditorUtility.SetDirty(selectObjectMesh);
                }
                else
                {
                    string _path = EditorUtility.SaveFilePanelInProject(Languages.GetValue( 21,"Save mesh"), "mesh", "mesh", Languages.GetValue(22, "save mesh to your project"));
                    if (_path.Length > 0)
                    {
                        //Debug.LogError(_path);
                        Mesh m = (Mesh)GameObject.Instantiate(selectObjectMesh);
                        AssetDatabase.CreateAsset(m, _path);
                        selectObjectMesh = (Mesh)AssetDatabase.LoadAssetAtPath<Mesh>(_path);
                        selectObject.sharedMesh = selectObjectMesh;
                        baseColors = selectObjectMesh.colors;
                    }
                }
            }
            EditorGUILayout.Space(20, true);
            EditorGUILayout.EndHorizontal();
        }
        
        /// <summary>
        /// 绘制纹理绘制面板
        /// </summary>
        void OnDrawTexturePainter()
        {
            EditorGUI.BeginChangeCheck();
            uvMark = (UVMark)EditorGUILayout.EnumPopup(Languages.GetValue(12, "UV Channel:"), uvMark);
            bool b = EditorGUI.EndChangeCheck();
            if (null == selectObject)
                return;             
            if (b)
            {
                DrawUV();
            }
            GUILayout.Label(Languages.GetValue(13, "Control Texture Prefix :") + setting.ctrlTexturePrefix);
            if (detectedCtrlTextureNames.Count > 0)
            {
                string detectedText = "Detected: ";
                for (int i = 0; i < detectedCtrlTextureNames.Count; i++)
                {
                    if (i > 0) detectedText += ", ";
                    detectedText += detectedCtrlTextureNames[i];
                }
                GUILayout.Label(detectedText);
            }
            GUILayout.Label(Languages.GetValue(59, "Texture2dArray :") + setting.mainTexArray);
            GUILayout.Label(Languages.GetValue(62, "Texture2dArray :") + setting.flowMapTextureName);
            
            
            selectObjectMaterial = null;
            if (null == selectMeshObjectRender)
            {
                selectMeshObjectRender = selectObject.gameObject.GetComponent<MeshRenderer>();
            }
            if (null != selectMeshObjectRender)
            {
                selectObjectMaterial = selectMeshObjectRender.sharedMaterial;
            }
             
            if (lastSelectObjectMaterial != selectObjectMaterial)
            {
                OnMaterialChange(lastSelectObjectMaterial);
                lastSelectObjectMaterial = selectObjectMaterial;
            }
            else
            {
                if (uvMark == UVMark.UV0)
                {
                    selectObjectMaterial.DisableKeyword("_CHANNEL_UV2");
                    selectObjectMaterial.DisableKeyword("_CHANNEL_UV1");
                    selectObjectMaterial.EnableKeyword("_CHANNEL_UV0");

                }
                else if (uvMark == UVMark.UV1)
                {
                    selectObjectMaterial.DisableKeyword("_CHANNEL_UV2");
                    selectObjectMaterial.DisableKeyword("_CHANNEL_UV0");
                    selectObjectMaterial.EnableKeyword("_CHANNEL_UV1");

                }
                else if (uvMark == UVMark.UV2)
                {
                    selectObjectMaterial.DisableKeyword("_CHANNEL_UV0");
                    selectObjectMaterial.DisableKeyword("_CHANNEL_UV1");
                    selectObjectMaterial.EnableKeyword("__CHANNEL_UV2");

                }
            }
            if (null == selectObjectMaterial)
            {
                // controlTextureCount 是只读属性，会自动返回0（当controlTextureManager为null时）
                // 清除控制图管理器缓存
                if (controlTextureManager != null)
                {
                    controlTextureManager.ClearCache();
                }
                editingChannel = -1;
            }
            else
            {
                GUILayout.Label(Languages.GetValue(15, "Editing channel:"));

                Texture2DArray t2d = null;
                Shader shader = selectObjectMaterial.shader;
                
                // 检测控制图
                DetectControlTextures(shader);
                
                // 初始化索引数组
                if (t2dAryIndex != null)
                {
                    int count = Mathf.Min(t2dAryIndex.Length, maxTextureCount);
                    for (int j = 0; j < count; j++)
                    {
                        t2dAryIndex[j] = j;
                    }
                }
                
                // 检测其他属性
                for (int i = 0; i < shader.GetPropertyCount(); i++)
                {
                    var ps = shader.GetPropertyAttributes(i);
                    string name = shader.GetPropertyName(i);
                    if (name == setting.mainTexArray)
                    {
                        t2d = (Texture2DArray)selectObjectMaterial.GetTexture(setting.mainTexArray);
                    }
                    // 动态检测所有可能的索引属性
                    if (t2dAryIndex != null)
                    {
                        int count = Mathf.Min(t2dAryIndex.Length, maxTextureCount);
                        for (int j = 0; j < count; j++)
                        {
                            if (name == setting.mainTexArrayIndex + j.ToString())
                            {
                                t2dAryIndex[j] = (int)selectObjectMaterial.GetFloat(name);
                            }
                        }
                    }
                }
                
                CheckIconArray(); 
                //当使用texture2dArray的时候
                if (selectTexture2dArray != t2d  && null != t2d)
                {
                    selectTexture2dArray = t2d;
                    CreateT2dAryIcons();
                }
                else
                {
                    //传统的传入贴图。贴图名称在设置面板.
                    CreateCommonIcons();
                }
                
                // flowmap在最后一张控制图的Alpha通道，如果没有控制图则使用独立flowmap
                if (hasFlowMap)
                {
                    if (controlTextureCount == 0)
                        flowMapEditing = true;
                    //flowMapEditing
                    flowMapEditing = EditorGUILayout.Toggle(Languages.GetValue(63, "Editoring Flow Map"), flowMapEditing);
                    if (flowMapEditing&&null != editorFlowMapRT)
                    {
                        if (GUILayout.Button("Smoonth FlowMap"))
                        {
                            SmoonthFlowMap();
                        }
                    }
                }
                else
                {
                    flowMapEditing = false;
                }
                
                //TODO: flowMapEditing
                if (!flowMapEditing)
                {
                    if (controlTextureCount > 0)
                    {
                        // 重放所有控制图
                        ReplayAllControlTextures();
                        
                        if (editingChannel < 0)
                            editingChannel = 0;
                        
                        // 使用动态的图标数组和列数
                        if (t2dAryIcons != null && t2dAryIcons.Length > 0)
                        {
                            // 计算合适的列数：每行显示8个，但不超过实际贴图数量
                            const int DEFAULT_GRID_COLUMNS = 8;
                            int columns = Mathf.Min(DEFAULT_GRID_COLUMNS, maxTextureCount);
                            // 如果贴图数量少于默认列数，使用实际数量作为列数
                            if (maxTextureCount < DEFAULT_GRID_COLUMNS)
                                columns = maxTextureCount;
                            
                            editingChannel = GUILayout.SelectionGrid(editingChannel, t2dAryIcons, columns);
                        }
                    }
                    else
                    {
                        ReplayFlowTexture();
                        editingChannel = -1;
                    }
                }
                
               
                EditorGUILayout.BeginHorizontal();
                if (GUILayout.Button(Languages.GetValue(16, "Save")))
                {
                    SaveTextures();
                }
                EditorGUILayout.Space(20, true);
                EditorGUILayout.EndHorizontal();
            }
        }

        /// <summary>
        /// 绘制绘制器主面板
        /// </summary>
        void OnDrawPainterPanel()
        {
            EditorGUI.BeginChangeCheck();
            selectObject = (MeshFilter)EditorGUILayout.ObjectField(Languages.GetValue(51, "Object to be planted"), selectObject, typeof(MeshFilter), true);
            bool selectObjectChanged = EditorGUI.EndChangeCheck();
            if (selectObjectChanged)
            {
                OnSelectObjectChange();
            }
            enable = DrawEnableCtrl(Languages.GetValue( 5,"Working .."), Languages.GetValue(6, "Disable"), enable);
            drawType = GUILayout.Toolbar(drawType, new string[] { Languages.GetValue(7, "Paint to texture"), Languages.GetValue(-8, "Paint to Vertex") });
            if (drawType == 0)
            {
                DrawTextureBrushsToolBar();
                OnDrawTexturePainter();
            }
            else
            {
                DrawVertexBrushsToolBar();
                OnDrawVertexPainter();
            }
            if (null != brushTexture)
            {
                if (null == perviewMat)
                {
                    perviewMat = new Material(Shader.Find("Hidden/PreviewTexture"));
                }
                Rect rect = GUILayoutUtility.GetRect(300f, 300f);
                rect.width = 300f;
                perviewMat.SetTexture("_Tex2", uvAreaPerviewTexture.texture);

                float h = window.position.height - rect.y-5;
                if (h > rect.width)
                {
                    rect.width = h;
                    rect.height = h;
                }
                EditorGUI.DrawPreviewTexture(rect, brushTexture, perviewMat);
            }
        }
    }
}

